package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.OrderCodeUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysStoreOpenService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 门店开单管理Controller
 * 
 * @author ruoyi
 * @date 2025-04-30
 */
@RestController
@RequestMapping("/system/storeOpen")
public class SysStoreOpenController extends BaseController
{
    @Autowired
    private ISysStoreOpenService sysStoreOpenService;
    @Autowired
    private SysMemberMapper sysMemberMapper;
    @Autowired
    private SysStoreMapper sysStoreMapper;
    @Autowired
    private SysMemberAddressMapper sysMemberAddressMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysStockMapper sysStockMapper;
    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    /**
     * 查询门店开单管理列表
     */
    // @PreAuthorize("@ss.hasPermi('system:storeOpen:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysStoreOpen sysStoreOpen)
    {
        if (ObjectUtils.isNotEmpty(sysStoreOpen.getOpenPhonenumber())) {
            SysUser sysUser = sysUserMapper.selectUserByPhone(sysStoreOpen.getOpenPhonenumber());
            sysStoreOpen.setCreateBy(sysUser.getUserId().toString());
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.isAdmin()){
            SysUser param = sysUserMapper.selectUserByPhone(sysStoreOpen.getPhonenumber());
            if (ObjectUtils.isNotEmpty(param)){
                sysStoreOpen.setCreateBy(param.getUserId().toString());
            }
        }
        startPage();
        List<SysStoreOpen> list = sysStoreOpenService.selectSysStoreOpenList(sysStoreOpen);
        for (SysStoreOpen item : list) {
            // 会员信息
//            SysMember sysMember = sysMemberMapper.selectSysMemberById(item.getMemberId());
            SysMember sysMember =  sysMemberMapper.selectSysMemberById(item.getMemberId());
            if (!ObjectUtils.isEmpty(sysMember)) {
                item.setMemberName(sysMember.getMemberName());
                item.setPhonenumber(sysMember.getPhonenumber());
            }
            // 门店信息
            SysStore sysStore = sysStoreMapper.selectSysStoreById(item.getStoreId());
            item.setStoreName(sysStore!=null ? sysStore.getStoreName() : null);
            //收货地址
            SysMemberAddress sysMemberAddress = sysMemberAddressMapper.selectSysMemberAddressById(item.getAddressId());
            if (!ObjectUtils.isEmpty(sysMemberAddress)) {
                item.setAddressName(sysMemberAddress.getAddressDetail());
                SysMember shMember =  sysMemberMapper.selectSysMemberByPhone(sysMemberAddress.getMemberId());
                if (!ObjectUtils.isEmpty(shMember)) {
                    item.setShName(shMember.getMemberName());
                    item.setShPhonenumber(shMember.getPhonenumber());
                }
            }
            // 开单员手机
            SysUser sysUser = sysUserMapper.selectUserById(Long.parseLong(item.getCreateBy()));
            if (!ObjectUtils.isEmpty(sysUser)) {
                item.setOpenPhonenumber(sysUser.getPhonenumber());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出门店开单管理列表
     */
    // @PreAuthorize("@ss.hasPermi('system:storeOpen:export')")
    @Log(title = "门店开单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysStoreOpen sysStoreOpen)
    {
        List<SysStoreOpen> list = sysStoreOpenService.selectSysStoreOpenList(sysStoreOpen);
        for (SysStoreOpen item : list) {
            if (!ObjectUtils.isEmpty(item.getMemberId())) {
                // 会员信息
                SysMember sysMember = sysMemberMapper.selectSysMemberById(item.getMemberId());
                if (!ObjectUtils.isEmpty(sysMember)) {
                    item.setMemberName(sysMember.getMemberName());
                    item.setPhonenumber(sysMember.getPhonenumber());
                }
                SysStore sysStore = sysStoreMapper.selectSysStoreById(item.getStoreId());
                if (ObjectUtils.isNotEmpty(sysStore)) {
                    item.setStoreName(sysStore.getStoreName());
                }
            }
        }
        ExcelUtil<SysStoreOpen> util = new ExcelUtil<SysStoreOpen>(SysStoreOpen.class);
        util.exportExcel(response, list, "门店开单管理数据");
    }

    /**
     * 获取门店开单管理详细信息
     */
    // @PreAuthorize("@ss.hasPermi('system:storeOpen:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(sysStoreOpenService.selectSysStoreOpenById(id));
    }

    /**
     * 新增门店开单管理
     */
    // @PreAuthorize("@ss.hasPermi('system:storeOpen:add')")
    @Log(title = "门店开单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysStoreOpen sysStoreOpen)
    {
        SysMember sysMember =  sysMemberMapper.selectSysMemberByPhone(sysStoreOpen.getPhonenumber());
        if (ObjectUtils.isEmpty(sysStoreOpen.getStoreId())){
            return AjaxResult.error("请选择门店");
        }
        if (ObjectUtils.isEmpty(sysStoreOpen.getSysMemberVoList())){
            return AjaxResult.error("请选择商品");
        }else{
//            List<SysStoreOpenVo> sysStoreOpenVos = sysStoreOpen.getSysMemberVoList();
//            for (SysStoreOpenVo item : sysStoreOpenVos) {
////                item
//            }

            if (!ObjectUtils.isEmpty(sysMember)) {
                sysStoreOpen.setMemberId(sysMember.getId());
            }
        }
        if (!SysUser.isAdmin(SecurityUtils.getLoginUser().getUserId())) {
            Long userId = SecurityUtils.getLoginUser().getUserId();
            String phonenumber = sysUserMapper.selectUserById(userId).getPhonenumber();
            sysStoreOpen.setPhonenumber(phonenumber);
        }
        String m = OrderCodeUtils.getOrderCode("M");
        if (!ObjectUtils.isEmpty(sysStoreOpen.getSysMemberVoList())) {
            BigDecimal resNum = new BigDecimal("0.00");
            int count = 0;

            List<SysStoreOpenVo> sysMemberVoList = sysStoreOpen.getSysMemberVoList();
            List<String> category = new ArrayList<>();
            Set<String> categorySet = new HashSet<>(category);
            for (SysStoreOpenVo item : sysMemberVoList) {
                // 临时拼接商品分类，后期需要修改

                GoodsCategory goodsCategory = goodsCategoryMapper.selectGoodsCategoryById(item.getCategoryId());
                if (!ObjectUtils.isEmpty(goodsCategory)) {
                    category.add(goodsCategory.getCategoryName());
                }
                categorySet.add(goodsCategory.getId());
                // 商品零售价 判断是否是会员
                String price = "0.00";
                if ("1".equals(sysMember.getStatus())){
                    price = item.getMemberMoney();
                }else{
                    price = item.getRetailPrice();
                }

                // 购买数量 * 零售价
                BigDecimal money = new BigDecimal(item.getPayNum()).multiply(new BigDecimal(price));
                // 计算总金额
                resNum = resNum.add(money);
                // 计算购买总数
                count += Integer.parseInt(item.getPayNum());

                // 添加门店开单详情
                SysStock sysStock = new SysStock();
                sysStock.setStoreStockId(m);
                sysStock.setMoney(price);
                sysStock.setDetailNum(item.getPayNum());
                sysStock.setStockType(item.getGoodsName());
                sysStockMapper.insertSysStock(sysStock);
            }
            sysStoreOpen.setGoodsCate(categorySet.size() + "");
            if (!ObjectUtils.isEmpty(category)) {
                sysStoreOpen.setGoodsCate(String.join(",",category));
            }

            sysStoreOpen.setPayNum(count + "");
            sysStoreOpen.setOrderMoney(resNum.toString());
        }

        sysStoreOpen.setGoodsCate(sysStoreOpen.getCategoryId());
        sysStoreOpen.setCreateBy(SecurityUtils.getLoginUser().getUserId() + "");
        sysStoreOpen.setOrderCode(m);
        return toAjax(sysStoreOpenService.insertSysStoreOpen(sysStoreOpen));
    }

    /**
     * 修改门店开单管理
     */
    // @PreAuthorize("@ss.hasPermi('system:storeOpen:edit')")
    @Log(title = "门店开单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysStoreOpen sysStoreOpen)
    {
        return toAjax(sysStoreOpenService.updateSysStoreOpen(sysStoreOpen));
    }

    /**
     * 删除门店开单管理
     */
    // @PreAuthorize("@ss.hasPermi('system:storeOpen:remove')")
    @Log(title = "门店开单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(sysStoreOpenService.deleteSysStoreOpenByIds(ids));
    }
}
